<template>
  <div class="blog-container">
    <!-- 新增轮播模块 -->
    <section class="featured-carousel">
      <div 
        v-for="(feature, index) in featured" 
        :key="index"
        class="carousel-item"
        :class="{ active: activeFeature === index }"
        @click="goToDetail(feature.id)"
      >
        <img :src="feature.image" :alt="feature.title" class="carousel-image">
        <div class="carousel-caption">
          <h3>{{ feature.title }}</h3>
          <p>{{ feature.excerpt }}</p>
        </div>
      </div>
      <button class="carousel-control prev" @click="prevFeature">&lt;</button>
      <button class="carousel-control next" @click="nextFeature">&gt;</button>
    </section>

    <!-- 原有搜索和分类模块 -->
    <div class="search-bar">
      <div class="search-input-group">
        <i class="fas fa-search"></i>
        <input
          v-model="searchQuery"
          type="text"
          placeholder="探索知识海洋..."
          @input="handleSearch"
        />
      </div>
      <div class="category-tags">
        <button
          v-for="category in categories"
          :key="category.id"
          :class="{ active: selectedCategory === category.id }"
          @click="toggleCategory(category.id)"
        >
          {{ category.name }}
        </button>
      </div>
    </div>

    <!-- 完整保留加载状态 -->
    <div v-if="loading" class="skeleton-loader">
      <div v-for="i in 3" :key="i" class="skeleton-card">
        <div class="skeleton-image"></div>
        <div class="skeleton-content"></div>
      </div>
    </div>

    <!-- 完整文章列表结构 -->
    <div v-else-if="articles.length === 0" class="no-results">
      <i class="fas fa-book-open"></i>
      <p>暂时没有找到相关内容</p>
    </div>
    <div v-else class="articles-grid">
      <article 
        v-for="article in articles" 
        :key="article.id" 
        class="article-card"
        @click="goToDetail(article.id)"
      >
        <div class="article-image">
          <img :src="article.coverImage || '/default-cover.jpg'" alt="文章封面">
        </div>
        <h2>
          <highlight-text :text="article.title" :keyword="searchQuery" />
        </h2>
        <div class="article-meta">
          <span class="category">{{ getCategoryName(article.categoryId) }}</span>
          <span class="date">{{ formatDate(article.createdAt) }}</span>
        </div>
        <p class="excerpt">
          <highlight-text :text="article.content.substring(0, 200) + '...'" :keyword="searchQuery" />
        </p>
        <div class="article-stats">
          <span class="views">👁️ {{ article.viewCount }}</span>
          <span class="likes">❤️ {{ article.likeCount }}</span>
        </div>
      </article>
    </div>

    <!-- 完整分页组件 -->
    <div class="pagination">
      <button
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
      >
        上一页
      </button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import HighlightText from '@/components/HighlightText.vue';

export default {
  name: 'BlogView',
  components: {
    HighlightText
  },
  data() {
    return {
      articles: [],
      categories: [],
      searchQuery: '',
      selectedCategory: '',
      currentPage: 1,
      pageSize: 10,
      totalPages: 1,
      loading: false,
      featured: [], // 新增轮播图数据
      activeFeature: 0, // 当前激活的轮播图索引
      intervalId: null // 轮播定时器
    };
  },
  created() {
    this.fetchArticles();
    this.fetchCategories();
    this.fetchFeatured(); // 获取轮播图数据
    this.startCarousel(); // 启动轮播
  },
  beforeDestroy() {
    this.stopCarousel(); // 销毁前停止轮播
  },
  methods: {
    async fetchArticles() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize
        };
        
        if (this.searchQuery) {
          params.keyword = this.searchQuery;
        }
        if (this.selectedCategory) {
          params.categoryId = this.selectedCategory;
        }

        const response = await axios.get('/api/blog/posts', { params });
        this.articles = response.data.data;
        this.totalPages = Math.ceil(response.data.total / this.pageSize);
      } catch (error) {
        console.error('Error fetching articles:', error);
      } finally {
        this.loading = false;
      }
    },
    async fetchCategories() {
      try {
        const response = await axios.get('/api/blog/categories');
        this.categories = response.data.data;
      } catch (error) {
        console.error('Error fetching categories:', error);
      }
    },
    async fetchFeatured() {
      try {
        const response = await axios.get('/api/blog/featured');
        this.featured = response.data.data;
      } catch (error) {
        console.error('Error fetching featured posts:', error);
      }
    },

    startCarousel() {
      this.intervalId = setInterval(() => {
        this.nextFeature();
      }, 5000);
    },

    stopCarousel() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },

    prevFeature() {
      this.activeFeature = (this.activeFeature - 1 + this.featured.length) % this.featured.length;
    },

    nextFeature() {
      this.activeFeature = (this.activeFeature + 1) % this.featured.length;
    },

    handleSearch() {
      this.currentPage = 1;
      this.fetchArticles();
    },
    handleCategoryChange() {
      this.currentPage = 1;
      this.fetchArticles();
    },
    changePage(page) {
      this.currentPage = page;
      this.fetchArticles();
    },
    getCategoryName(categoryId) {
      const category = this.categories.find(c => c.id === categoryId);
      return category ? category.name : '未分类';
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    },
    goToDetail(id) {
      this.$router.push(`/blog/${id}`);
    }
  }
};
</script>

<style scoped>
.blog-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  margin-top: 40px;
  width: 100%;

}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  
}

.search-bar input,
.search-bar select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  font-size: 14px;
  background-color: var(--bg-color);
  color: var(--text-color);
}

.search-bar input {
  flex: 1;
  border: 2px solid var(--border-color);
}

.articles-list {
  display: grid;
  gap: 20px;
}

.category-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 15px;
  
  button {
    padding: 8px 16px;
    border-radius: 20px;
    background: var(--tag-bg);
    border: 1px solid var(--border-color);
    transition: all 0.2s ease;
    position: relative;
    overflow: hidden;
    
    &.active {
      background: var(--primary-color);
      color: white;
      border-color: transparent;
      box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    &:not(.active):hover {
      background: var(--tag-hover-bg);
      transform: translateY(-2px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }
    
    &::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(255,255,255,0.1);
      opacity: 0;
      transition: opacity 0.2s;
    }
    
    &:active::after {
      opacity: 1;
    }
  }
}
.article-card {
  background: var(--card-bg);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--shadow);
  cursor: pointer;
  transition: var(--transition);
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--hover-shadow);
}

.article-card h2 {
  margin: 0 0 10px 0;
  color: var(--heading-color);
}

.article-meta {
  display: flex;
  gap: 15px;
  color: var(--text-secondary);
  font-size: 14px;
  margin-bottom: 10px;
}

.excerpt {
  color: var(--text-secondary);
  margin: 10px 0;
  line-height: 1.5;
}

.article-stats {
  display: flex;
  gap: 15px;
  color: var(--text-tertiary);
  font-size: 14px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination button {
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background: var(--card-bg);
  color: var(--text-color);
  cursor: pointer;
  transition: var(--transition);
}

.pagination button:hover:not(:disabled) {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.pagination button:disabled {
  background: var(--disabled-bg);
  color: var(--text-tertiary);
  cursor: not-allowed;
}

.loading,
.no-results {
  text-align: center;
  padding: 20px;
  color: var(--text-secondary);
}


.article-image {
  height: 200px;
  overflow: hidden;
  border-radius: 8px 8px 0 0;
  position: relative;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s ease;
  }

  @media (max-width: 768px) {
    height: 180px;
    border-radius: 6px 6px 0 0;
  }
}

.articles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;

  @media (max-width: 768px) {
    grid-template-columns: 1fr;
    gap: 20px;
  }
}

/* 轮播图样式 */
.featured-carousel {
  position: relative;
  overflow: hidden;
  margin-bottom: 30px;
}

.carousel-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  opacity: 0;
  transition: opacity 0.5s ease-in-out;
}

.carousel-item.active {
  opacity: 1;
}

.carousel-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

.carousel-caption {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  text-align: center;
}

.carousel-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
}

.prev {
  left: 10px;
}

.next {
  right: 10px;
}

</style>